﻿using Common.Core.Cache;
using Common.Core.Extensions;
using Common.Core.Helpers.Json;
using Microsoft.Extensions.Caching.StackExchangeRedis;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Unicode;

namespace Common.Cache.Redis
{
    public static class RedisCacheExtensions
    {
        /// <summary>
        /// 配置redis缓存组件，业务通过CacheHelper调用此组件
        /// </summary>
        /// <param name="services"></param>
        /// <param name="Configuration"></param>
        public static void AddRedisCache(this IServiceCollection services, IConfiguration Configuration)
        { 
            // 是否启用redis
            bool IsUseRedis = Configuration.GetSection("CacheProvider:UseRedis").Value.ToBool(false);
            if (IsUseRedis)
            {
                string connectionString = Configuration.GetSection("CacheProvider:Redis:ConnectionString").Value;
                string instanceName = Configuration.GetSection("CacheProvider:Redis:InstanceName").Value;
                int dbNum = Configuration.GetSection("CacheProvider:Redis:DbNum").Value.ToInt(0);

                var options = new JsonSerializerOptions()
                {
                    Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),
                    WriteIndented = true
                };
                //设置时间格式
                options.Converters.Add(new DateTimeJsonConverter());
                options.Converters.Add(new DateTimeNullableConverter());
                //设置bool获取格式
                options.Converters.Add(new BooleanJsonConverter());
                //设置数字
                options.Converters.Add(new IntJsonConverter());


                //Use Redis
                services.AddStackExchangeRedisCache(options =>
                {
                    options.Configuration = connectionString;
                    options.InstanceName = instanceName;
                });
                services.AddSingleton(typeof(ICacheService), new RedisCacheService(new RedisCacheOptions
                {
                    Configuration = connectionString,
                    InstanceName = instanceName,
                }, options, dbNum));
                // services.Configure<DistributedCacheEntryOptions>(option => option.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5));//设置Redis缓存有效时间为5分钟。
            }
        }
    }
}
